package com.spps;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileSystem {
    public static boolean isDirectory(String pathname) {
        return new File(pathname).isDirectory();
    }

    public static String getDirectoryName(String pathname) {
        return pathname.substring(0, pathname.lastIndexOf("/")) + "/";
    }

    public static String getFileName(String pathname) {
        return new File(pathname).getName();
    }

    public static String getExtension(String pathname) {
        String[] segments = pathname.split("\\.");
        return segments[segments.length - 1];
    }

    public static File[] listFiles(String pathname) throws Exception {
        if (!FileSystem.isDirectory(pathname)) {
            throw new Exception("The pathname must be a directory.");
        }
        return new File(pathname).listFiles();
    }

    public static boolean mkdirs(String pathname) {
        if (FileSystem.exists(pathname)) {
            return false;
        }
        return new File(pathname).mkdirs();
    }

    public static String getFileContent(String filePath) {
        String content = "";
        try {
            // 打开文件读取流
            FileInputStream fis = new FileInputStream(filePath);
            // 读取文件内容得到一个 ASCII 码数组集合
            byte[] bytes = fis.readAllBytes();
            // 关闭文件读取流
            fis.close();
            // 循环打印每个字符
            for (int i = 0; i < bytes.length; i++) {
                // ASCII码转字符
                char character = (char) bytes[i];
                // 打印结果
                content += character;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    public static void saveFileContent(String content, String filePath) {
        if (!FileSystem.exists(FileSystem.getDirectoryName(filePath))) {
            FileSystem.mkdirs(FileSystem.getDirectoryName(filePath));
        }
        try {
            // 打开对文件的写入流
            FileOutputStream fos = new FileOutputStream(filePath);
            // 需要提供字母的ASCII码
            for (int i = 0; i < content.length(); i++) {
                fos.write(Integer.valueOf(content.charAt(i)));
            }
            // 关闭对文件的写入流
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean exists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }
}
